<template>
  <div>
    <el-card>
      <div slot="header">
        <span>赛事报名</span>
      </div>
      <div>
        <el-table :data="upcomingEvents" style="width: 100%" v-loading="loading">
          <el-table-column prop="eventName" label="赛事名称"></el-table-column>
          <el-table-column prop="location" label="比赛地点"></el-table-column>
          <el-table-column label="报名状态">
            <template slot-scope="scope">
              {{ getRegistrationStatus(scope.row.eventId) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button 
                v-if="!isRegistered(scope.row.eventId)"
                @click="handleRegister(scope.row)" 
                type="primary" 
                size="small"
                :loading="scope.row.registerLoading"
              >
                报名
              </el-button>
              <el-button 
                v-else-if="canCancel(scope.row.eventId)"
                @click="handleCancel(scope.row)" 
                type="danger" 
                size="small"
                :loading="scope.row.cancelLoading"
              >
                退报
              </el-button>
              <span v-else>不可退报</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      upcomingEvents: [],
      loading: false,
      registrations: []
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        await Promise.all([this.fetchEvents(), this.fetchRegistrations()]);
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$message.error('初始化数据失败');
      } finally {
        this.loading = false;
      }
    },
    async fetchEvents() {
      try {
        const response = await axios.get('http://localhost:10086/team/events');
        this.upcomingEvents = response.data.data
          .filter(event => event.status === 'upcoming')
          .map(event => ({
            ...event,
            registerLoading: false,
            cancelLoading: false
          }));
      } catch (error) {
        console.error('获取赛事列表失败:', error);
        throw error;
      }
    },
    async fetchRegistrations() {
      try {
        const response = await axios.get('http://localhost:10086/team/registrations', {
          params: { teamId: this.$store.state.userId }
        });
        this.registrations = response.data.data || [];
      } catch (error) {
        console.error('获取报名信息失败:', error);
        throw error;
      }
    },
    getRegistrationStatus(eventId) {
      const registration = this.registrations.find(reg => 
        reg.event && reg.event.eventId === eventId
      );
      
      if (!registration) return '未报名';
      
      const statusMap = {
        'pending': '审核中',
        'approved': '报名通过',
        'rejected': '报名未通过'
      };
      return statusMap[registration.status] || registration.status;
    },
    isRegistered(eventId) {
      return this.registrations.some(reg => 
        reg.event && reg.event.eventId === eventId
      );
    },
    canCancel(eventId) {
      const registration = this.registrations.find(reg => 
        reg.event && reg.event.eventId === eventId
      );
      return registration && registration.status !== 'approved';
    },
    async handleRegister(event) {
      try {
        event.registerLoading = true;
        await this.$confirm(`确定要报名参加"${event.eventName}"吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await axios.post(
          `http://localhost:10086/team/event/${event.eventId}/register`,
          { teamId: this.$store.state.userId }
        );
        
        if (response.data.code === 200) {
          this.$message.success('报名成功，等待审核');
          await this.fetchRegistrations();
        } else {
          this.$message.error(response.data.message || '报名失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('报名失败:', error);
          this.$message.error(error.response?.data?.message || '报名失败');
        }
      } finally {
        event.registerLoading = false;
      }
    },
    async handleCancel(event) {
      try {
        event.cancelLoading = true;
        await this.$confirm(`确定要取消报名"${event.eventName}"吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await axios.delete(
          `http://localhost:10086/team/event/${event.eventId}/cancel`,
          { params: { teamId: this.$store.state.userId } }
        );
        
        if (response.data.code === 200) {
          this.$message.success('退报成功');
          await this.fetchRegistrations();
        } else {
          this.$message.error(response.data.message || '退报失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退报失败:', error);
          this.$message.error(error.response?.data?.message || '退报失败');
        }
      } finally {
        event.cancelLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.el-card {
  margin: 20px;
}
.el-table {
  margin-top: 10px;
}
</style>